//
//  JMPhoneCodePopupView.m
//  NewiOSProject
//
//  Created by li on 2023/9/12.
//  Copyright © 2023 范智渊. All rights reserved.
//

#import "JMPhoneCodePopupView.h"
#import "LayoutView.h"

#import "JMPickerSelectionView.h"
#import "JMPickerSelectionModel.h"
#import "PaddingView.h"
#import "LayoutScrollView.h"
#import "CustomStackView.h"
#import "CustomStackView.h"
#import "LayoutView.h"
#import "UIView+PopupProtocol.h"
@interface JMPhoneCodePopupView ()<UITextFieldDelegate>

@property(nonatomic, strong) PaddingView *rootView;
@property(nonatomic, strong) LayoutScrollView *contentStack;
@property(nonatomic, strong) PaddingView *inputPaddingView;
@property (nonatomic, assign)BOOL timing;//验证码倒计时进行中
@property(nonatomic, strong) UIButton *closeBtn;

@end

@implementation JMPhoneCodePopupView
@synthesize modalStyle;
@synthesize translucentView;
@synthesize dismissCompletion;
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:(UIKeyboardWillShowNotification) object: nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillDismiss:) name:UIKeyboardWillHideNotification object: nil];
        self.translucentView = [self defaultTranslucentView];
        self.modalStyle = PopupViewModalStyleFromBottom;
        [self setupViews];
        
        self.heightConstraint = [self.heightAnchor constraintEqualToConstant:400];
        self.heightConstraint.active = YES;
    }
    return self;
}

- (void)setupViews {
    
    LayoutScrollView *contentStack = [LayoutScrollView new];
    contentStack.rootStack.layoutViewAlignment = LayoutViewAlignmentTop;
    contentStack.rootStack.contentView.axis = UILayoutConstraintAxisVertical;
    
    self.rootView = [PaddingView initWithContentView:contentStack edgeInsets:(UIEdgeInsetsMake(70, 20, 60, 20))];
    self.rootView.backgroundColor = [UIColor whiteColor];
    
    [self addSubview:self.rootView];
    self.rootView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    
    // gradient
//    CAGradientLayer *gl = [CAGradientLayer layer];
//    gl.frame = CGRectMake(0,0,kScreenWidth,398);
//    gl.startPoint = CGPointMake(0.5, 0.04);
//    gl.endPoint = CGPointMake(0.5, 0.37);
//    gl.colors = @[(__bridge id)[UIColor colorWithRed:251/255.0 green:255/255.0 blue:211/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0].CGColor];
//    gl.locations = @[@(0), @(1.0f)];
//    [self.rootView.layer insertSublayer:gl atIndex:0];
    
//    UIImageView *bg = [UIImageView new];
//    bg.image = [UIImage imageNamed:@"phone_code_bg"];
//    bg.translatesAutoresizingMaskIntoConstraints = NO;
//    [self.rootView addSubview:bg];
//    [NSLayoutConstraint activateConstraints:@[
//        [bg.topAnchor constraintEqualToAnchor:self.rootView.topAnchor],
//        [bg.leftAnchor constraintEqualToAnchor:self.rootView.leftAnchor],
//        [bg.rightAnchor constraintEqualToAnchor:self.rootView.rightAnchor],
//    ]];
    
//    Número de cuenta corriente
    UILabel *title = [UILabel new];
    title.text = @"Cuenta actualmente iniciada";
    title.font = [UIFont systemFontOfSize:18 weight:(UIFontWeightBold)];
    title.textColor = [UIColor colorWithHexString:@"#222222"];
    [contentStack.rootStack addContentView:title];
    
    UILabel *phone = [UILabel new];
//    phone.text = @"+25 0000000";
    phone.text = [NSString stringWithFormat:@"+52 %@", [JMProjectManager sharedJMProjectManager].loginUser.phone];
    phone.font = [UIFont systemFontOfSize:16 weight:(UIFontWeightRegular)];
    phone.textAlignment = NSTextAlignmentLeft;
    phone.textColor = [UIColor colorWithHexString:@"#0F1511"];
    [contentStack.rootStack addContentView:phone];
    [contentStack.rootStack.contentView setCustomSpacing:30 afterView:title];
    [contentStack.rootStack.contentView setCustomSpacing:20 afterView:phone];
    
    CustomStackView *codeStack = [CustomStackView new];
    
    UITextField *code = [UITextField new];
    code.textColor = [UIColor colorWithHexString:@""];
    code.font = [UIFont systemFontOfSize:14];
    code.textColor = Text_COLOR_LEVEL1();
    code.keyboardType = UIKeyboardTypeNumberPad;
    code.placeholder = @"Código de verificación";
    self.textField = code;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChangeValue:) name:UITextFieldTextDidChangeNotification object:self.textField];

    [codeStack addArrangedSubview:code];
    [codeStack addArrangedSubview:self.fetchCodeBtn];
    [_fetchCodeBtn.rightAnchor constraintEqualToAnchor:codeStack.rightAnchor];
    [_fetchCodeBtn.heightAnchor constraintEqualToAnchor:codeStack.heightAnchor];
    
    PaddingView *codeStackPaddingView = [PaddingView initWithContentView:codeStack edgeInsets:(UIEdgeInsetsMake(0, 0, 0, 0))];
    [contentStack.rootStack addContentView: codeStackPaddingView];
    codeStackPaddingView.translatesAutoresizingMaskIntoConstraints = NO;
    [codeStackPaddingView.widthAnchor constraintEqualToAnchor: contentStack.widthAnchor].active = YES;
    [codeStackPaddingView.heightAnchor constraintEqualToConstant:46].active = YES;
    self.inputPaddingView = codeStackPaddingView;
    
    CustomStackView *lineStack = [CustomStackView init:(UILayoutConstraintAxisHorizontal)];
    lineStack.backgroundColor = mainSepartorColor();
    [lineStack.heightAnchor constraintEqualToConstant:1].active = YES;
    [contentStack.rootStack addContentView:lineStack];
    
   

    UILabel *warning = [UILabel new];
    warning.text = @" ";
    warning.font = [UIFont systemFontOfSize:12 weight:(UIFontWeightRegular)];
    warning.textAlignment = NSTextAlignmentLeft;
    warning.numberOfLines = 0;
    warning.textColor = [UIColor colorWithHexString:@"#FF3F33"];
    [warning.heightAnchor constraintEqualToConstant:25].active = YES;

    self.warnLab = warning;
    [contentStack.rootStack addContentView:warning];
    [contentStack.rootStack.contentView setCustomSpacing:10 afterView:codeStackPaddingView];
    
    [self.rootView bringSubviewToFront:contentStack];
    [contentStack.rootStack.contentView setCustomSpacing:20 afterView:warning];
    
  
    [contentStack.rootStack addContentView:self.confirmView];
    
   

}
#pragma mark - keyboard 监听
- (void)keyboardWillShow: (NSNotification *)aNofitication {
    self.heightConstraint.constant = 600;
    [UIView animateWithDuration:0.25 animations:^{
        
        [self.superview layoutIfNeeded];
    }];
    
}

- (void)keyboardWillDismiss: (NSNotification *)aNofitication {
    self.heightConstraint.constant = 400;
    [UIView animateWithDuration:0.25 animations:^{
        
        [self.superview layoutIfNeeded];
    }];
}

- (void)popup:(UIView *)rootView edgeInsets:(UIEdgeInsets)edgeInsets {
    [super popup:rootView edgeInsets:edgeInsets];
    [rootView addSubview:self.closeBtn];
    [self.closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.mas_right).offset(-24);
        make.top.equalTo(self.mas_top).offset(24);
        make.width.height.equalTo(@37);
    }];
    
    [self.fetchCodeBtn fire];
    [self.textField becomeFirstResponder];
}

- (void)dismissPopup {
    [super dismissPopup];
    [self.closeBtn removeFromSuperview];
    [self.fetchCodeBtn stopTimer];
    self.textField.text = @"";
    [self.textField resignFirstResponder];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {

}
- (void)textFieldDidChangeValue:(NSNotification *)notification
{
    UITextField *sender = (UITextField *)[notification object];
//
//    if (sender.text.length) {
//        self.warnLab.hidden = YES;
//    }else{
//        self.warnLab.hidden = NO;
//    }
}
#pragma mark - 懒加载
- (JMAuthentiactionConfirmView *)confirmView {
    if (!_confirmView) {
        self.confirmView = [JMAuthentiactionConfirmView new];
        _confirmView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        [_confirmView.confirmBut addTarget:self action:nil forControlEvents:(UIControlEventTouchUpInside)];
        _confirmView.reading.hidden = YES;
        _confirmView.rootView.edgeInsets = UIEdgeInsetsZero;
        [_confirmView.confirmBut setTitle:@"Entregar" forState:(UIControlStateNormal)];
    }
    return _confirmView;
}


-(void)updateUI{
    [_fetchCodeBtn.rightAnchor constraintEqualToAnchor:_fetchCodeBtn.superview.rightAnchor];
    [_fetchCodeBtn.heightAnchor constraintEqualToAnchor:_fetchCodeBtn.superview.heightAnchor];
    [_fetchCodeBtn startLoading];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.fetchCodeBtn stopTimer];
}
-(void)fetchBtnClick:(JMCaptcheButton *)sender{
    [self updateUI];
    self.warnLab.text = @"";
    NSDictionary *param;
    param =  @{@"phone":JMProjectManager.sharedJMProjectManager.loginUser.phone,@"type":@"modify_bank",@"voiceCode":@"false"};
    [sender fire];
    
    [[JMBaseRequest sharedInstance] requestBasePost:BasePostRequestUrl(loginSendSms) params:param success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        [JMProgressHelper toastInWindowWithMessage:@"Código de verificación por SMS obtenido con éxito"];
    } fail:^(NSString * _Nonnull errorMsg) {
        [JMProgressHelper toastInWindowWithMessage:errorMsg];
    }];
    
}
-(JMCaptcheButton *)fetchCodeBtn{
    if (!_fetchCodeBtn) {
        //获取验证码
        _fetchCodeBtn = [JMCaptcheButton new];
        _fetchCodeBtn.interval = 60;
        _fetchCodeBtn.cornerRadius = 5;
        _fetchCodeBtn.disabledTitleColor = Hex_Str_COLOR(@"#0F1511");
        _fetchCodeBtn.titleLabel.font = Font(14);
        [_fetchCodeBtn setTitle:@"Obtener" forState:(UIControlStateNormal)];
        [_fetchCodeBtn addTarget:self action:@selector(fetchBtnClick:)
                forControlEvents:(UIControlEventTouchUpInside)];
        [_fetchCodeBtn setTitleColor:Hex_Str_COLOR(@"#0F1511") forState:(UIControlStateNormal)];
        _fetchCodeBtn.selected = YES;
    }
    return _fetchCodeBtn;
}
-(UIButton *)closeBtn{
    if (!_closeBtn) {
        _closeBtn = [JMControl createButtonWithFrame:(CGRectZero) ImageName:@"auth_close" Target:self Action:@selector(dismissPopup) font:nil Title:nil];
    }
    return _closeBtn;
}

@end
